<template>
  <div class="min-h-full w-full overflow-x-hidden bg-white p-6">
    <a-card class="mx-auto max-w-2xl" title="🎲 随机数生成器">
      <a-space direction="vertical" class="w-full" size="large">
        <!-- 参数设置 -->
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="最小值">
              <a-input-number
                v-model:value="minValue"
                :min="0"
                :max="999999"
                class="w-full"
                placeholder="0"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="最大值">
              <a-input-number
                v-model:value="maxValue"
                :min="1"
                :max="1000000"
                class="w-full"
                placeholder="100"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="生成数量">
          <a-slider
            v-model:value="count"
            :min="1"
            :max="20"
            :marks="countMarks"
            class="w-full"
          />
          <div class="mt-2 text-center">
            <a-tag color="blue">{{ count }} 个</a-tag>
          </div>
        </a-form-item>

        <!-- 高级选项 -->
        <a-collapse>
          <a-collapse-panel key="1" header="高级选项">
            <a-space direction="vertical" class="w-full">
              <a-checkbox v-model:checked="allowDuplicates">
                允许重复数字
              </a-checkbox>
              <a-checkbox v-model:checked="sortResults">
                自动排序结果
              </a-checkbox>
              <a-checkbox v-model:checked="showHex"> 显示十六进制 </a-checkbox>
            </a-space>
          </a-collapse-panel>
        </a-collapse>

        <!-- 生成按钮 -->
        <a-button
          type="primary"
          size="large"
          @click="generateRandomNumbers"
          class="w-full"
          :icon="h('span', { class: 'text-lg' }, '🎲')"
        >
          生成随机数
        </a-button>

        <!-- 结果显示 -->
        <a-card v-if="results.length > 0" size="small" title="生成结果">
          <a-space direction="vertical" class="w-full">
            <div class="flex flex-wrap gap-2">
              <a-tag
                v-for="(num, index) in results"
                :key="index"
                :color="getTagColor(index)"
                class="px-3 py-1 text-base"
              >
                {{ showHex ? '0x' + num.toString(16).toUpperCase() : num }}
              </a-tag>
            </div>

            <!-- 统计信息 -->
            <a-divider v-if="results.length > 1" />
            <a-row v-if="results.length > 1" :gutter="16">
              <a-col :span="8">
                <a-statistic title="最小值" :value="stats.min" />
              </a-col>
              <a-col :span="8">
                <a-statistic title="最大值" :value="stats.max" />
              </a-col>
              <a-col :span="8">
                <a-statistic
                  title="平均值"
                  :value="stats.average"
                  :precision="2"
                />
              </a-col>
            </a-row>

            <!-- 复制结果 -->
            <div class="mt-4 text-center">
              <a-space>
                <a-button size="small" @click="copyResults">
                  复制结果
                </a-button>
                <a-button size="small" @click="exportResults">
                  导出数据
                </a-button>
              </a-space>
            </div>
          </a-space>
        </a-card>

        <!-- 错误提示 -->
        <a-alert
          v-if="error"
          :message="error"
          type="error"
          show-icon
          closable
          @close="error = ''"
        />

        <!-- 历史记录 -->
        <a-card v-if="history.length > 0" size="small" title="历史记录">
          <a-list size="small" :data-source="history">
            <template #renderItem="{ item }">
              <a-list-item>
                <a-space class="w-full justify-between">
                  <span>{{ item.time }}</span>
                  <a-space>
                    <a-tag>{{ item.count }}个</a-tag>
                    <a-tag>{{ item.range }}</a-tag>
                    <a-button
                      type="link"
                      size="small"
                      @click="loadHistory(item)"
                    >
                      加载
                    </a-button>
                  </a-space>
                </a-space>
              </a-list-item>
            </template>
          </a-list>
          <a-button type="link" size="small" @click="clearHistory" class="mt-2">
            清空历史
          </a-button>
        </a-card>
      </a-space>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, h } from 'vue'
import { message } from 'ant-design-vue'

interface HistoryItem {
  time: string
  count: number
  range: string
  results: number[]
  stats: {
    min: number
    max: number
    average: number
  }
}

const minValue = ref(0)
const maxValue = ref(100)
const count = ref(5)
const results = ref<number[]>([])
const error = ref('')
const allowDuplicates = ref(true)
const sortResults = ref(false)
const showHex = ref(false)
const history = ref<HistoryItem[]>([])

const countMarks = {
  1: '1个',
  5: '5个',
  10: '10个',
  15: '15个',
  20: '20个',
}

const stats = computed(() => {
  if (results.value.length === 0) return { min: 0, max: 0, average: 0 }

  const min = Math.min(...results.value)
  const max = Math.max(...results.value)
  const average =
    results.value.reduce((a, b) => a + b, 0) / results.value.length

  return {
    min,
    max,
    average: Number(average.toFixed(2)),
  }
})

const getTagColor = (index: number) => {
  const colors = [
    'blue',
    'green',
    'orange',
    'red',
    'purple',
    'cyan',
    'geekblue',
  ]
  return colors[index % colors.length]
}

const generateRandomNumbers = () => {
  // 验证参数
  if (minValue.value >= maxValue.value) {
    error.value = '最小值必须小于最大值！'
    results.value = []
    return
  }

  error.value = ''
  results.value = []

  // 生成随机数
  const availableNumbers = maxValue.value - minValue.value + 1

  if (!allowDuplicates.value && count.value > availableNumbers) {
    error.value = `在${minValue.value}-${maxValue.value}范围内无法生成${count.value}个不重复的随机数！`
    return
  }

  const tempResults: number[] = []
  const usedNumbers = new Set<number>()

  for (let i = 0; i < count.value; i++) {
    let randomNum: number

    if (allowDuplicates.value) {
      randomNum =
        Math.floor(Math.random() * (maxValue.value - minValue.value + 1)) +
        minValue.value
    } else {
      // 不允许重复时，确保生成不重复的随机数
      do {
        randomNum =
          Math.floor(Math.random() * (maxValue.value - minValue.value + 1)) +
          minValue.value
      } while (usedNumbers.has(randomNum))
      usedNumbers.add(randomNum)
    }

    tempResults.push(randomNum)
  }

  if (sortResults.value) {
    tempResults.sort((a, b) => a - b)
  }

  results.value = tempResults

  // 添加到历史记录
  const historyItem: HistoryItem = {
    time: new Date().toLocaleString(),
    count: count.value,
    range: `${minValue.value}-${maxValue.value}`,
    results: [...results.value],
    stats: { ...stats.value },
  }

  history.value.unshift(historyItem)
  if (history.value.length > 10) {
    history.value.pop()
  }

  message.success(`成功生成${count.value}个随机数！`)
}

const copyResults = async () => {
  const text = results.value.join(', ')
  try {
    await navigator.clipboard.writeText(text)
    message.success('结果已复制到剪贴板！')
  } catch (err) {
    message.error('复制失败，请手动复制')
  }
}

const exportResults = () => {
  const data = {
    time: new Date().toLocaleString(),
    parameters: {
      min: minValue.value,
      max: maxValue.value,
      count: count.value,
      allowDuplicates: allowDuplicates.value,
      sortResults: sortResults.value,
    },
    results: results.value,
    statistics: stats.value,
  }

  const blob = new Blob([JSON.stringify(data, null, 2)], {
    type: 'application/json',
  })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `random-numbers-${Date.now()}.json`
  a.click()
  URL.revokeObjectURL(url)

  message.success('数据已导出！')
}

const loadHistory = (item: HistoryItem) => {
  results.value = item.results
  minValue.value = parseInt(item.range.split('-')[0])
  maxValue.value = parseInt(item.range.split('-')[1])
  count.value = item.count
  message.info('已加载历史记录')
}

const clearHistory = () => {
  history.value = []
  message.info('历史记录已清空')
}

// 初始化生成随机数
generateRandomNumbers()
</script>

<style scoped></style>
